<template>
  <div class="index">
    <div class="index_header">
      <van-popover v-model:show="bookVisible">
        <div class="sheet_add_book sheet_book_list" @click="handleGoBookManage">
          <i class="iconfont icon-jia"></i>
          <span class="sheet_text">添加账本</span>
        </div>
        <div class="sheet_book_list" v-for="(item, index) in bookData" :key="'book' + index" @click="handleSwitchBook(item)">
          <i :class="['iconfont', item.icon]"></i>
          <span class="sheet_text">{{ item.name }}</span>
        </div>
        <div style="text-align: center;" @click="bookVisible = false">取消</div>
        <template #reference>
          <div class="header_title">
            <div @click.stop="bookVisible = true">
              <i class="iconfont icon_benzi" :class="[bookInfo?.icon]"></i> {{ bookInfo?.name }}
            </div>
          </div>
        </template>
      </van-popover>
      <div class="header_button">
        <i class="iconfont icon-sousuo" @click="handleGoSearch"></i>
        <i class="iconfont icon-gengduo"></i>
      </div>
    </div>
    <div class="index_number">
      <div class="number_save">
        <div class="numebr_save_month">
          <div class="number_title">本月收入</div>
          <div class="number_save_money">{{ incomeTotal }}</div>
        </div>
        <div class="numebr_save_month">
          <div class="number_title">本月结余</div>
          <div class="number_save_money">{{ (incomeTotal - payTotal).toFixed(2) }}</div>
        </div>
        <div class="numebr_save_month" @click="handleGoSetBudget">
          <div class="number_title">剩余预算</div>
          <div class="number_save_money">{{ (monthBudget - payTotal).toFixed(2) }}</div>
        </div>
      </div>
      <div class="number_outer">
        <div class="number_outer_month">
          <div class="number_title">本月支出</div>
          <div class="number_outer_money">{{ payTotal }}</div>
        </div>
      </div>
    </div>
    <div class="index_button" @click="handleGoBppkKeeping">
      <i class="iconfont icon-tianjia"></i>
        添加一条新记账
    </div>
    <div class="index_list">
      <budget-bar :budget="monthBudget" :pay="payTotal"></budget-bar>
      <daily-bill-card 
        v-for="(card, index) in billCardList" 
        :key="'card' + index" 
        :data="card" 
        :multiple-show="editBillList"
      ></daily-bill-card>
    </div>
  </div>
</template>

<script lang="ts">
import { getBudget } from '@/api/budget'
import BudgetBar from '@/components/budget/BudgetBar.vue'
import { getStartAndEnd } from '@/utils/helper'
import dayjs from 'dayjs'
import { computed, defineComponent, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import DailyBillCard from '../components/bill/DailyBillCard.vue'
export default defineComponent({
  name: 'Home',
  components: {
    DailyBillCard,
    BudgetBar,
},
  setup() {
    const router = useRouter()
    const store = useStore()
    const billCardList = computed(() => store.state.billList)
    const budgetVisible = ref(false)
    const payTotal = computed(() => store.state.billTotal.pay)
    const incomeTotal = computed(() => store.state.billTotal.income)
    const bookVisible = ref(false)
    const editBillList = computed(() => !store.state.footerVisible)
    const bookData = computed(() => store.state.bookList)
    const bookInfo = computed(() => store.state.book)
    const monthBudget = ref(0)
    // 点击开始记账，跳转到记账页
    const handleGoBppkKeeping = () => {
      setTimeout(() => {
        router.push('/bookkeeping')
      }, 200)
    }
    // 获取账单数据列表
    const getBillCardList = (start: string, end: string) => {
      store.dispatch('fetchBillList', {
        end: end,
        start: start,
        type: 'day',
        bookIds: bookInfo.value.id
      })
    }
    // 获取当月预算
    const handleGetBudget = () => {
      getBudget({
        id: bookInfo.value.id,
        date: dayjs().format('YYYY-MM')
      }).then((res) => {
        if(typeof res.code === 'number' && res.code === 100) {
          monthBudget.value = res.data ? res.data.budget : 0
        }
      })
    }
    // 点击预算，跳转到设置预算页
    const handleGoSetBudget = () => {
      router.push('/setBudget')
    }
    // 获取当月收入/支出总金额
    const handleGetSumRange = (start: string, end: string) => {
      store.dispatch('fetchBillTotal', {
        end: end,
        start: start,
        type: 'month',
        bookIds: bookInfo.value.id
      })
    }
    // 新增账本，跳转到账本管理页
    const handleGoBookManage = () => {
      router.push('/bookManage')
    }
    // 切换账本
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const handleSwitchBook = (book: any) => {
      bookVisible.value = false
      localStorage.setItem('book', JSON.stringify(book))
      store.commit('get_book', book)
      handleGetData(true)
    }
    // 初始化获取各种数据
    const handleGetData = (must?: boolean) => {
      console.log(store.state.billList, '145');
      const date = getStartAndEnd(new Date())
      const start = dayjs(date.start).format('YYYY-MM-DD 00:00:00')
      const end = dayjs(date.end).format('YYYY-MM-DD 23:59:59')
      handleGetBudget()
      if(!store.state.billList || (!store.state.billList.length) || must) {
        getBillCardList(start, end)
        handleGetSumRange(start, end)
      }
      if(store.state.classList.length === 0 || store.state.classList.length === 1) {
        store.dispatch('fetchClassList')
      }
      if(!store.state.bookList.length) {
        store.dispatch('fetchBookList').then(() => {
          const bookList = store.state.bookList
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          bookList.forEach((book: any) => {
            if(book.defaultBook) {
              localStorage.setItem('book', JSON.stringify(book))
              store.commit('get_book',JSON.parse(localStorage.getItem('book') as string))
            }
          });
        })
      }
    }
    // 跳转到搜索账单页面
    const handleGoSearch = () => {
      router.push('/searchBill')
    }
    onMounted(() => {
      if(localStorage.getItem('book')) {
        store.commit('get_book',JSON.parse(localStorage.getItem('book') as string))
      } else {
        const bookList = store.state.bookList
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        bookList.forEach((book: any) => {
          if(book.defaultBook) {
            localStorage.setItem('book', JSON.stringify(book))
            store.commit('get_book',JSON.parse(localStorage.getItem('book') as string))
          }
        });
      }
      handleGetData()
    })
    return {
      store,
      billCardList,
      budgetVisible,
      incomeTotal,
      payTotal,
      bookVisible,
      bookData,
      bookInfo,
      editBillList,
      monthBudget,
      handleGoBppkKeeping,
      handleGoSetBudget,
      handleGoBookManage,
      handleSwitchBook,
      handleGoSearch
    }
  }
})
</script>

<style scoped lang="scss">
  @import url('../assets/iconfont/iconfont.css');
  .index_header {
    display: flex;
    justify-content: space-between;
    font-size: 20px;
    position: fixed;
    top: 0;
    padding: 30px 0 10px;
    width: calc(100% - 20px);
    z-index: 8;
    background-color: #fff;
  }
  .index {
    margin: 20px 10px;
  }
  .icon_benzi {
    color: #F9C3C2;
    font-size: 20px;
    padding: 0 4px;
    font-weight: 600;
  }
  .header_title {
    position: relative;
  }
  .book_sheet {
    position: absolute;
    background-color: #fff;
    padding: 10px 20px;
    width: 50vw;
    left: -2px;
    box-shadow: #ccc 4px 4px 10px 1px;
    font-size: 16px;
    text-align: left;
  }
  .sheet_book_list {
    line-height: 30px;
  }
  .sheet_text {
    margin-left: 10px;
  }
  .icon-sousuo, .icon-gengduo {
    color: #F9C3C2;
    font-size: 20px;
    padding: 0 8px;
  }
  .index_number {
    padding: 20px;
    margin: 70px 0 20px 0;
    background-image: url("../assets/picture/home.png");
    text-align: left;
    border-radius: 14px;
  }
  .number_save {
    display: flex;
    padding-bottom: 20px;
  }
  .numebr_save_month {
    margin-right: 30px;
  }
  .number_title {
    color: #64687c;
    padding-bottom: 6px;
  }
  .number_save_money {
    color: #333;
    font-size: 22px;
  }
  .number_outer_money {
    font-size: 30px;
    color: #eb7775;
  }
  .index_button {
    background-color: #F9C3C2;
    height: 60px;
    border-radius: 12px;
    line-height: 60px;
    font-size: 18px;
    color: #fff;
    position: relative;
    z-index: 1;
    overflow: hidden;
  }
  .index_button::before {
    content: "";
    position: absolute;
    z-index: -1;
    top: 50%;
    left: 50%;
    width: 26px;
    height: 26px;
    transform: translate3d(-50%,-50%,0) scale(0,0);
    border-radius: 50%;
    background-color: #ffd7d6;
    transform-origin: center;
    transition: ease-in-out 0.2s;
  }
  .index_button:active::before {
    transform: translate3d(-50%,-50%,0) scale(15,15);
  }
  .icon-tianjia {
    font-size: 20px;
  }
  .index_list {
    margin-top: 20px;
    overflow-y: auto;
    height: calc(100vh - 420px);
  }
  .van-popover--light .van-popover__content {
    margin-left: 20%;
  }
</style>